package com.wut.core.config.exception;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.wut.core.common.enums.ResponseMessageEnum;
import com.wut.core.common.vo.ErrorResponse;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ErrorResponse handleException(MethodArgumentNotValidException exception, HttpServletRequest request) {
        ErrorResponse response = new ErrorResponse();
        BindingResult result = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            if (!errors.isEmpty()) {
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    stringBuilder.append(fieldError.getDefaultMessage()).append(";");
                });
            }
        }
        response.setMessage(stringBuilder.toString());
        response.setCode(HttpStatus.HTTP_INTERNAL_ERROR);
        //TODO 后期用于日志跟踪
        response.setRequestId("");
        response.setRequestURI(request.getRequestURI());
        response.setRequestMethod(request.getMethod());
        return response;
    }

    @ExceptionHandler(Exception.class)
    public ErrorResponse handleException(Exception ex, HttpServletRequest request) {
        log.error(ex.getMessage(), ex);
        ErrorResponse response = new ErrorResponse();
        if (ex instanceof GlobalException) {
            GlobalException globalException = (GlobalException) ex;
            response.setMessage(StrUtil.blankToDefault(ex.getMessage(), ResponseMessageEnum.getRespMessage(request.getMethod()) + "失败"));
            response.setCode(globalException.getCode());
        } else {
            response.setCode(HttpStatus.HTTP_INTERNAL_ERROR);
            response.setMessage("内部错误");
        }
        //TODO 后期用于日志跟踪
        response.setRequestId("");
        response.setRequestURI(request.getRequestURI());
        response.setRequestMethod(request.getMethod());
        return response;
    }
}